package com.ys.controller.api.purchase;

import com.ys.config.MenuId;
import com.ys.entity.purchase.TcgOfflinePurchaseInStorage;
import com.ys.entity.sys.YsCol;
import com.ys.enume.sys.YsColEnum;
import com.ys.service.business.YsbExportLogService;
import com.ys.service.purchase.TcgOfflinePurchaseInStorageService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService;
import com.ys.util.DateUtil;
import com.ys.util.ExportExcelUtils;
import com.ys.util.admin.ConditionUtil;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @Author: fxz
 * @CreateTime: 2024-11-14
 * @Description: 线上采购入库单
 * @Version: 1.0
 */
@Controller
@RequestMapping("/api/inter/tcgOfflinePurchaseInStorage")
public class TcgOfflinePurchaseInStorageController {

    private static final Logger logger = LoggerFactory.getLogger(TcgOfflinePurchaseInStorageController.class);

    @Autowired
    private TcgOfflinePurchaseInStorageService tcgOfflinePurchaseInStorageService;

    //菜单id
    private Long menuId = MenuId.TCG_OfflinePurchaseInStorage;

    private Long menuIdBc = MenuId.TCG_OfflinePurchaseInStorageBc;

    @Autowired
    private CommonApiService<TcgOfflinePurchaseInStorage> commonApiService;

    //权限字符
    private final String PERMISSIONS_VIEW = "tcgOfflinePurchaseInStorage:view";

    @Autowired
    private YsbExportLogService ysbExportLogService;

    /**
     * 物流信息修改
     */
    @RequiresPermissions("tcgPurchaseOrderWc:update")
    @RequestMapping("/wlUpdate")
    @ResponseBody
    public R wlUpdate(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            return tcgOfflinePurchaseInStorageService.wlUpdate(params);
        } catch (IllegalArgumentException e) {
            return R.error(e.getMessage());
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }

    /**
     * 查询
     */
    @RequiresPermissions(PERMISSIONS_VIEW)
    @RequestMapping("/search")
    @ResponseBody
    public LayuiTableVoJA search(Model model, HttpServletRequest request, HttpServletResponse response,
                                 @ModelAttribute TcgOfflinePurchaseInStorage cond, String conditions
    ){
        try {
            cond = setSeachSql(cond,conditions);
            LayuiTableVoJA setList = commonApiService.searchLay(cond);

            return setList;
        }catch (Exception e){
            logger.error("查询出错：",e.getMessage(),e);
            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
            tableVoJA.setCode(1);
            tableVoJA.setMsg("查询出错，请稍后重试！");
            return tableVoJA;
        }
    }

    /**
     * 设置查询的cond的sql设置
     * @param cond
     * @return
     */
    public TcgOfflinePurchaseInStorage setSeachSql(TcgOfflinePurchaseInStorage cond, String conditions){
        //查询条件
        String nameLinked = ConditionUtil.getConditionValue(conditions, "_ys_storageStatusNew");//入库状态
        if (nameLinked != null){
            if (!nameLinked.equals("5")){
                cond.where("(case when A.storageStatus != 0 then A.storageStatus else " +
                        "(case when DATEDIFF(day, A.CreateTime,GETDATE())  >= 6 then 4 else A.storageStatus end) end) =" + nameLinked);
            }
        }else {
            cond .where("A.storageStatus = 0");
        }
        String _ys_estimatedStorageTime = ConditionUtil.getConditionValue(conditions, "_ys_estimatedStorageTime");//预计入库时间
        if (_ys_estimatedStorageTime != null && _ys_estimatedStorageTime.length() > 0) {
            String[] timeDays = _ys_estimatedStorageTime.split(" ~ ");
            cond.where("(DATEADD(day, 3, A.CreateTime)) >= '" + timeDays[0] + "' and (DATEADD(day, 3, A.CreateTime)) <= '" + timeDays[1] + "'");
        }
        cond
                .addLeftJoin("TCG_PurchaseByOrderSon C ON C.id = A.PurchaseOrderSonId")
                .addLeftJoin("TCG_PurchaseByOrder AA ON C.Pid = AA.id")
                .addField("AA.AliOrderNumber AS aliOrderNumber,AA.Bid purchaseOrderBid,AA.id purchaseOrderId")//1688订单编号
                .addLeftJoin("THR_OperateCompanyApply E ON E.Vgsbm = A.Vgsbm ")//运营公司管理表
                .addField("E.Vgsjc AS vgsjc")//采购公司简称
                .addField("E.Vgsmc AS vgsmc")//采购公司名称
                .addLeftJoin("TCG_PurchaseByPlan H ON H.Bid = AA.PlanBid")//采购计划表
                .addField("H.bid AS purchasePlanBid")//计划单号
                .addField("DATEADD(day, 3, A.CreateTime)  AS _ys_estimatedStorageTime")//预计入库时间
                .addField("case when A.storageStatus != 0 then A.storageStatus else " +
                        "(case when DATEDIFF(day, A.CreateTime,GETDATE())  >= 6 then 4 else A.storageStatus end) end as _ys_storageStatusNew")//入库状态
                .addLeftJoin("TCC_Location CC ON CC.Chw = A.Chw")
                .addLeftJoin("TCC_WarehouseArea CWA ON CWA.Ckq = CC.Ckq")//库区
                .addLeftJoin("TCC_Warehouse CW ON CW.Cck = CWA.Cck")//仓库
                .addField("CW.vck,CWA.vkq,CC.vhw")
                .addLeftJoin("TS_UserChange B on B.Id = E.OperatorChangeId")
                .addField("B.UserId operatorUserId")//运营人工号
                .addField("B.UserName operatorUserName")//运营人
                .setOrderby("A.Bid DESC");//排序

        cond = commonApiService.dataAuth(menuId, cond);

        return  cond;
    }

    @RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute TcgOfflinePurchaseInStorage cond, String conditions) throws Exception{

        cond.setPage(0).setSize(999999);
        cond = setSeachSql(cond,conditions);

        List<Map<String, Object>> listData = cond.queryMap();


        List<YsCol> listField = new YsCol()
                .setMenuId(menuId)
                .setFrontShow(YsColEnum.FrontShow.SHOW.value)
                .setOrderby("A.SortNo asc")
                .queryList();

        ExportExcelUtils<TcgOfflinePurchaseInStorage> util = new ExportExcelUtils<TcgOfflinePurchaseInStorage>(new TcgOfflinePurchaseInStorage());

        String toFilePath = util.exportExcel(listData, listField, "线上采购入库表");
        UploadService.UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
        return R.ok(dto.getUrl());
    }

    @RequestMapping("/exportBc")
    @ResponseBody
    public R exportBc(@ModelAttribute TcgOfflinePurchaseInStorage cond, String aliLogisticsBillNoList,String bid) throws Exception{
        YsbExportLogService.ExportDto dto1 = ysbExportLogService.init(menuIdBc);
        try {
            List<Map<String, Object>> listData = new ArrayList<>();
            String[] aliLogisticsBillNos = aliLogisticsBillNoList.substring(0, aliLogisticsBillNoList.length() - 1).split(",");
            for (String aliLogisticsBillNo : aliLogisticsBillNos) {
                Map<String, Object> dataMap = new HashMap<>();
                dataMap.put("aliLogisticsBillNo", aliLogisticsBillNo);
                listData.add(dataMap);
            }

            List<YsCol> listField = new YsCol()
                    .setMenuId(menuIdBc)
                    .setFrontShow(YsColEnum.FrontShow.SHOW.value)
                    .setOrderby("A.SortNo asc")
                    .queryList();
            ExportExcelUtils<TcgOfflinePurchaseInStorage> util = new ExportExcelUtils<TcgOfflinePurchaseInStorage>(new TcgOfflinePurchaseInStorage());

            String toFilePath = util.exportExcel(listData, listField, "标记报错-" + bid);
            UploadService.UploadDto dto2 = commonApiService.uploadLocalToServer(toFilePath);
            ysbExportLogService.updateSuccess(dto1.getId(), dto2.getUrl(), bid);
            return com.ys.vo.R.ok("已经生成完毕");
        }catch (Exception e){
            ysbExportLogService.updateFail(dto1.getId(),bid);
            return com.ys.vo.R.error("生成失败，请联系客服");
        }
    }

    /**
     * 取消入库
     */
    @RequiresPermissions("tcgOfflinePurchaseInStorage:qxrk")
    @RequestMapping("/cancelStorage")
    @ResponseBody
    public R cancelStorage(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            return tcgOfflinePurchaseInStorageService.cancelStorage(params);
        } catch (IllegalArgumentException e) {
            return R.error(e.getMessage());
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }

    /**
     * 采购入库
     */
    @RequiresPermissions("tcgOfflinePurchaseInStorage:edit")
    @RequestMapping("/updateRk")
    @ResponseBody
    public R updateRk(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            //采购入库
            return tcgOfflinePurchaseInStorageService.updateRk(params);
        } catch (Exception e) {
            logger.error("采购入库出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        }
    }



    /**
     * 弹出框（根据母件编码调取子件信息）
     */
    @RequestMapping("/searchByPcode")
    @ResponseBody
    public LayuiTableVoJA searchByPcode(Model model, HttpServletRequest request, HttpServletResponse response,
                                        @ModelAttribute TcgOfflinePurchaseInStorage cond, String conditions){
        try {


            String _ys_pCode = ConditionUtil.getConditionValue(conditions, "_ys_pCode");//母件编码
            if (_ys_pCode != null) {
                cond.setMainTable("(SELECT AA.SubCode AS Id, AA.ProductCode,AA.SubCode,AA.SubName,SUM(AA.SubBomNumber) AS SubBomNumber FROM" +
                        " TCG_OfflinePurchaseInStorage AA LEFT JOIN TCC_OfflineAssembleItem B ON AA.Id = B.OfflinePurchaseStorageId WHERE B.Id IS NOT NULL AND AA.ProductCode ='" + _ys_pCode + "' GROUP BY AA.ProductCode,AA.SubCode,AA.SubName)");
                cond.where("A.ProductCode ='" + _ys_pCode + "'");
            }

            cond.setFields("A.Id,A.ProductCode AS  _ys_pCode,A.SubCode AS  code,A.SubName AS  name,A.SubBomNumber AS  num");
            //cond.addField("A.SubCode AS  code");//子件编码
            //cond.addField("A.SubName AS  name");//子件名称
            //cond.addField("A.SubBomNumber AS  num");//子件BOM数量


            LayuiTableVoJA tableVoJA = commonApiService.searchLay(cond);
            return tableVoJA;
        }catch (Exception e){
            logger.error("查询Listing库出错：",e.getMessage(),e);
            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
            tableVoJA.setCode(1);
            tableVoJA.setMsg("查询出错，请稍后重试！");
            return tableVoJA;
        }
    }



    /**
     * 弹出框（根据母件编码调取子件信息）
     */
    @RequestMapping("/searchByPcodeSearch")
    @ResponseBody
    public R searchByPcodeSearch(Model model, HttpServletRequest request, HttpServletResponse response, String _ys_pCode, Long stockControlId){
        try {
            TcgOfflinePurchaseInStorage cond = new TcgOfflinePurchaseInStorage();
            cond.setMainTable("(SELECT AA.SubCode AS Id, AA.ProductCode,AA.SubCode,AA.SubName,(AA.SubBomNumber) AS SubBomNumber FROM" +
                    " TCG_OfflinePurchaseInStorage AA LEFT JOIN TCC_OfflineAssembleItem B ON AA.Id = B.OfflinePurchaseStorageId " +
                    "LEFT JOIN TCC_StockControlRunning C ON C.StockControlId = " + stockControlId +
                    "LEFT JOIN TCC_StockSource D ON D.AssembleBid = B.pbid AND D.IsNewInventory = 1 AND D.StockControlRunningId = C.id "  +
                    "WHERE B.Id IS NOT NULL AND AA.ProductCode ='" + _ys_pCode + "' AND D.id IS NOT NULL)");
            cond.where("A.ProductCode ='" + _ys_pCode + "'");

            cond.setFields("A.Id,A.ProductCode AS  _ys_pCode,A.SubCode AS  code,A.SubName AS  name,A.SubBomNumber AS  num");

            List<Map<String,Object>> resDate = cond.queryMap();

            return R.ok("成功",resDate);
        }catch (Exception e){
            logger.error("查询出错：",e.getMessage(),e);
            return R.error("查询出错，请稍后重试！");
        }
    }

}
